﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;
namespace Presentation
{
    public partial class frmQuanLyNguoiDung : DevComponents.DotNetBar.Office2007Form
    {
        DataTable dt = new DataTable();
        DataView dv = new DataView();
        bool save;
        private bool isFormClosing = false;
        // Contant for the close message
        private const int WM_CLOSE = 16;
        //override the WndProc msg to trap the WM_CLOSE message
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_CLOSE)
                isFormClosing = true;
            base.WndProc(ref m);
        }
        public frmQuanLyNguoiDung()
        {
            InitializeComponent();
            dgvNguoiDung.AutoGenerateColumns = false;
            DataGridViewComboBoxColumn colChucVu = new DataGridViewComboBoxColumn();
            colChucVu.DataSource = ChucVuService.GetChucVuTable();
            colChucVu.ValueMember = "MaChucVu";
            colChucVu.DataPropertyName = "MaChucVu";
            colChucVu.DisplayMember = "TenChucVu";
            colChucVu.Name = "ChucVu";
            colChucVu.HeaderText = "Chức vụ";
            colChucVu.Width = 200;
            

            dgvNguoiDung.Columns.Add(colChucVu);
        }

        private void frmQuanLyNguoiDung_Load(object sender, EventArgs e)
        {
            LoadGridView();
        }
        private void LoadGridView()
        {
            dt=NguoiDungService.GetNguoiDungTable();
            dt.TableName="NguoiDung";
            dt.AcceptChanges();
            dgvNguoiDung.DataSource =dt;
            dv.Table=dt;
            save = false;
            dgvNguoiDung.ReadOnly = false;
            btnCapNhat.Enabled = true;
        }
        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            if (CapNhat())
                MessageBoxEx.Show("Đã cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private bool KiemTraTenDangNhapTrenGrid(string tenDangNhap,int rowIndex)
        {
            for (int i = 0; i <rowIndex; i++)
            {
                if (tenDangNhap == dgvNguoiDung["TenDangNhap", i].EditedFormattedValue.ToString())
                    return true;
            }
            return false;
        }
        //Cập nhật
        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();

            List<NguoiDungDTO> listThem = new List<NguoiDungDTO>();
            for (int i = 0; i < dtThem.Rows.Count;i++ )
            {
                string tenDangNhap, hoTen, maChucVu;

                tenDangNhap=dtThem.Rows[i]["TenDangNhap"].ToString();
                hoTen=dtThem.Rows[i]["HoTen"].ToString();
                maChucVu = dtThem.Rows[i]["MaChucVu"].ToString();
                int i_MaChucVu;
                if(tenDangNhap=="" || hoTen=="" || !int.TryParse(maChucVu,out i_MaChucVu))
                    return false;

                NguoiDungDTO nguoiDung = new NguoiDungDTO();
                nguoiDung.TenDangNhap = tenDangNhap;
                nguoiDung.MatKhau = "";
                nguoiDung.HoTen = hoTen;
                nguoiDung.MaChucVu =i_MaChucVu;
                nguoiDung.TinhTrang = 1;
                listThem.Add(nguoiDung);
            }

            List<NguoiDungDTO> listCapNhat = new List<NguoiDungDTO>();
            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {
                string tenDangNhap, hoTen, maChucVu;

                tenDangNhap = dtCapNhat.Rows[i]["TenDangNhap"].ToString();
                hoTen = dtCapNhat.Rows[i]["HoTen"].ToString();
                maChucVu = dtCapNhat.Rows[i]["MaChucVu"].ToString();
                int i_MaChucVu;
                if (tenDangNhap == "" || hoTen == "" || !int.TryParse(maChucVu, out i_MaChucVu))
                    return false;

                NguoiDungDTO nguoiDung = new NguoiDungDTO();
                nguoiDung.TenDangNhap = tenDangNhap;
                nguoiDung.MatKhau = "";
                nguoiDung.HoTen = hoTen;
                nguoiDung.MaChucVu = i_MaChucVu;
                nguoiDung.TinhTrang = 1;
                listCapNhat.Add(nguoiDung);
            }
            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                string tenDangNhap = dtXoa.Rows[i]["TenDangNhap"].ToString();
                NguoiDungService.Delete(tenDangNhap);
            }

            foreach (NguoiDungDTO nd in listCapNhat)
                NguoiDungService.Update(nd);
            foreach (NguoiDungDTO nd in listThem)
                NguoiDungService.Insert(nd);
           
            btnCapNhat.Enabled = false;
            dgvNguoiDung.ReadOnly = true;
            save = false;
            return true;
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvNguoiDung_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (isFormClosing) 
                return;
            if (e.RowIndex == dgvNguoiDung.RowCount - 1)
                return;
            if (e.FormattedValue.ToString() == "")
            {
                MessageBoxEx.Show("Không được bỏ trống!","Lỗi!",MessageBoxButtons.OK,MessageBoxIcon.Error);
                e.Cancel = true;
                return;
            }

            if (KiemTraTenDangNhapTrenGrid(e.FormattedValue.ToString(),e.RowIndex))
            {
                MessageBoxEx.Show("Tên đăng nhập này đã tồn tại!", "Lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                dgvNguoiDung.CurrentCell = dgvNguoiDung["TenDangNhap", e.RowIndex];
                dgvNguoiDung.BeginEdit(true);
                e.Cancel = true;
                return;
            }
        }

        private void dgvNguoiDung_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (isFormClosing)
                return;
            if (e.RowIndex == dgvNguoiDung.RowCount - 1)
                return;
            for (int i = 0; i < dgvNguoiDung.ColumnCount; i++)
            {
                if (dgvNguoiDung[i, e.RowIndex].EditedFormattedValue.ToString() == "")
                {
                    MessageBoxEx.Show("Không được bỏ trống!", "Lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dgvNguoiDung.CurrentCell = dgvNguoiDung[i, e.RowIndex];
                    dgvNguoiDung.BeginEdit(true);
                    e.Cancel = true;
                    return;
                }
            }
            
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadGridView();
        }

        private void dgvNguoiDung_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
            {
                DataGridViewComboBoxEditingControl cb = e.Control as DataGridViewComboBoxEditingControl;
                cb.DropDownStyle = ComboBoxStyle.DropDown;
                cb.AutoCompleteSource = AutoCompleteSource.ListItems;
                cb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

                cb.SelectedIndex = -1;
            }
        }

        private void dgvNguoiDung_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            save = true;
        }

        private void frmQuanLyNguoiDung_FormClosing(object sender, FormClosingEventArgs e)
        {
        //    if (btnCapNhat.Enabled && save)
        //    {
        //        DialogResult r = MessageBoxEx.Show("Bạn có muốn lưu lại các thông tin?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        //        if (r == DialogResult.Cancel)
        //        {
        //            e.Cancel = true;
        //            isFormClosing = false;
        //        }
        //        else if (r == DialogResult.Yes)
        //        {
        //            if (!CapNhat())
        //            {
        //                MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                e.Cancel = true;
        //                isFormClosing = false;
        //            }
        //        }
        //    }
        }
    }
}
